﻿using System.Text;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Utilities.Encoders;


namespace AllEncryption
{
    public class SM3Util
    {
        public static string SignatureBySM3(string src,string key)
        {
            return Hex.ToHexString(GetEncryptByKey(src,key));
        }
        public static byte[] GetEncryptByKey(string src,string key)
        {
            byte[] msg = Encoding.UTF8.GetBytes(src);
            byte[] keyByte = Encoding.UTF8.GetBytes(key);

            KeyParameter keyParameter = new KeyParameter(keyByte);            
            SM3Digest sm3 = new SM3Digest();
            HMac hMac = new HMac(sm3);
            hMac.Init(keyParameter);
            hMac.BlockUpdate(msg,0,msg.Length);
            byte[] result = new byte[hMac.GetMacSize()];
            hMac.DoFinal(result,0);
            return result;
        }
        public static bool VerifyBySM3(string src,string key, string rs)
        {
            if(rs == null||src==null)
                return false;
           
            byte[] newHashCode = GetEncryptByKey(src,key);
            var hexData = Hex.ToHexString(newHashCode);
            return rs.Length== hexData.Length &&rs.SequenceEqual(hexData);
        }     

        
    }
}
